

import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from 'axios'

interface axiosConfig extends AxiosRequestConfig {
    showLoading?: boolean
}


const baseURL:string = "http://10.2.19.130:3050"


export function axiosInstance(config?: axiosConfig): AxiosInstance {
  const instance = axios.create({
    baseURL:baseURL,
    timeout: 10000, // 超时配置
    withCredentials: true, // 跨域携带cookie
    ...config, // 自定义配置覆盖基本配置
  })

  // const showLoading = config?.showLoading === undefined ? true : config?.showLoading

  // 添加请求拦截器
  instance.interceptors.request.use(
    (config: any) => {
      return config
    },
    (error) => {
      return Promise.reject(error)
    },
  )

  // 添加响应拦截器
  instance.interceptors.response.use(
    (response:any) => {
      const { code,data,message} = response.data
      //後端需具體返回message，將message全部提示系統異常！
      //將data解構，不需要臃腫的response
      //console.log(response.headers)
      if (code === 200 && data.length !== 0) { return Promise.resolve({code:200,data:data,message:message}) }
      //操作類的sql返回執行成功
      else if(code === 200 && data.length === 0){
        return Promise.resolve({code:200,message:message})
      }
      //服務端組件發送請求時會發送數據
      else if(code !== 200){
        return Promise.reject({code:code,message:message})
      }

      else {
        //獲取文件流時返回
        if(response.headers["content-type"] === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          response.headers["content-type"] === "application/octet-stream" ||
          response.headers["content-type"] === "image/svg+xml; charset=utf-8"
        ){
          return Promise.resolve(response.data)
        }
        else
         return data
      }
    },
    (error) => {
        return Promise.reject(error)
    },
  )
  return instance
}
